package com.zeta.plan.realm;

import com.zeta.plan.model.JWTToken;
import com.zeta.plan.service.UserService;
import com.zeta.plan.utils.JWTUtil;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

/**
 * @ClassName CustomRealm
 * @Description TODO
 * @Author zeta
 * @Date 2022/2/25 16:42
 * @Version 1.0
 **/
@Component
public class CustomRealm extends AuthorizingRealm {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserService userService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }

    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        // 从token中拿到username
        String username = JWTUtil.getUsername(principalCollection.toString());

        return null;
    }

    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // 拿到token
        String token = (String)authenticationToken.getCredentials();
        String username = JWTUtil.getUsername(token);
        boolean enabled = false;

        // 判断用户是否合法
        if (!redisTemplate.hasKey(username + ":info")) {
            enabled = userService.findEnabledByUsername(username);
            System.out.println(enabled);
        } else {
            enabled = (boolean)redisTemplate.opsForHash().get(username + ":info", "enabled");
        }

        if (enabled) {
            return new SimpleAuthenticationInfo(token, token, "customRealm");
        } else {
            throw new AuthenticationException("认证失败！");
        }
    }
}
